package com.boot.unity.api.modules.train.service.impl;

import com.boot.unity.api.modules.train.constants.StepConstant;
import com.boot.unity.api.modules.train.dao.StuDao;
import com.boot.unity.api.modules.train.dao.StudentDao;
import com.boot.unity.api.modules.train.dto.StudentDTO;
import com.boot.unity.api.modules.train.entity.Stu;
import com.boot.unity.api.modules.train.entity.Student;
import com.boot.unity.api.modules.train.result.Result;
import com.boot.unity.api.modules.train.service.StudentService;
import com.boot.unity.api.modules.train.service.StudentUpdateDataService;
import com.boot.unity.api.utils.DateUtil;
import com.boot.unity.api.utils.IdUtil;
import com.boot.unity.api.utils.ImageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author anonymous
 * @create 2020-09-07 22:14:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {
    private final StuDao stuDao;
    private final StudentDao studentDao;
    private final ApplicationEventPublisher publisher;
    private final StudentUpdateDataService studentUpdateDataService;
    /**
     * 报名人像照片
     */
    @Value("${train.signup.avatar.path}")
    private String signupAvatarPath;

    private static final List<Integer> UPDATE_TYPE = Arrays.asList(0, 1, 2);

    @Override
    public Result save(Student student) {
        try {
            String studentId = student.getStudentId();
            Student s = studentDao.getByStudentId(studentId);
            if (s != null) {
                return Result.fail("保存报名信息失败,学员ID[" + studentId + "]已存在!");
            }
            // ① 处理人像照片
            String base64Image = student.getPhoto();
            if (StringUtils.isNotBlank(base64Image)) {
                // 替换一下，防止+在传输过程中丢失
                base64Image = base64Image.replace(" ", "+");
                String absolutePath = signupAvatarPath + ImageUtil.getPath() + IdUtil.uuid() + ".jpg";
                String url = absolutePath.replace(signupAvatarPath, "");
                boolean b = ImageUtil.generateImage(base64Image, absolutePath);
                if (!b) {
                    return Result.fail("保存人像图片失败!");
                }
                student.setPhoto(null);
                student.setPhotoPath(absolutePath);
                student.setPhotoUrl(url);
            }
            studentDao.save(student);
            //进行学员报名信息的绑定
            //studentId = student.getStudentId();
            /*String cardNo = student.getCardNo();
            String trainType = student.getTrainType();
            stuDao.updateStuForStudentId(studentId,cardNo,trainType);*/
            studentUpdateDataService.upStudentForStatus(studentId);


            return Result.success("保存报名信息成功!");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存报名信息失败:[{}]", student);
        }
        return Result.fail("保存报名信息失败!");
    }

    @Override
    public Result update(StudentDTO studentDTO) {
        Integer updateType = studentDTO.getUpdateType();
        if (!UPDATE_TYPE.contains(updateType)) {
            return Result.fail("更新类型不正确!");
        }
        String studentId = studentDTO.getStudentId();
        if (StringUtils.isBlank(studentId)) {
            return Result.fail("学员ID不能为空!");
        }
        Student s = studentDao.getByStudentId(studentId);

        boolean isSave = false;
        if (s == null) {
            isSave = true;
            //return Result.fail("系统中无学员ID为["+studentId+"]的信息!");
        }
        String cardNo = studentDTO.getCardNo();
        //String step = studentDTO.getStep();
        Student student = new Student();
        BeanUtils.copyProperties(studentDTO, student);
        switch (updateType) {
            case 0:
                // 基本信息
                if (isSave) {
                    studentDao.saveBase(student);
//                        if (StepConstant.STEP_SYNC.contains(step)){
//                            publisher.publishEvent(cardNo);
//                        }
                    studentUpdateDataService.upStudentForStatus(studentId);
                    return Result.success("保存基本信息成功!");
                } else {
                    if(!studentDTO.getCardType().equals(s.getCardType())){
                        student.setStatus("0");
                    }else{
                        student.setStatus(null);
                    }
                    studentDao.updateBase(student);
                    studentUpdateDataService.upStudentForStatus(studentId);
                        /*
                        boolean flag = studentUpdateDataService.upStudentForStatus(studentId);
//                        boolean flag = upStudentForStatus(studentId);
                       */
                    return Result.success("更新基本信息成功!");
                }
            case 1:
                // 人像信息
                String base64Image = student.getPhoto();
                if (StringUtils.isBlank(base64Image)) {
                    return Result.fail("人像图片不能为空!");
                }
                String absolutePath = signupAvatarPath + ImageUtil.getPath() + IdUtil.uuid() + ".jpg";
                String url = absolutePath.replace(signupAvatarPath, "");
                boolean b = ImageUtil.generateImage(base64Image, absolutePath);
                if (!b) {
                    return Result.fail("保存人像图片失败!");
                }
                student.setPhoto(null);
                student.setPhotoPath(absolutePath);
                student.setPhotoUrl(url);
                if (isSave) {
                    studentDao.savePhoto(student);
//                        if (StepConstant.STEP_SYNC.contains(step)){
//                            publisher.publishEvent(cardNo);
//                        }
                    //studentUpdateDataService.upStudentForStatus(studentId);
                    return Result.success("保存人像图片成功!");
                } else {
                    studentDao.updatePhoto(student);
                    return Result.success("更新人像图片成功!");
                }

            case 2:
                // 状态信息
                String step = student.getStep();
                if (StepConstant.STEP_5.equals(step)){
                    // 当前时间的字符串表示
                    student.setSignupDate(DateUtil.getNormalDateTimeString());
                    //studentUpdateDataService.upStudentForStatus(studentId);
                }
                if (isSave) {
                    studentDao.saveStep(student);
                    if (StepConstant.STEP_SYNC.contains(step)){
                        publisher.publishEvent(cardNo);
                    }
                    //studentUpdateDataService.upStudentForStatus(studentId);
                    return Result.success("保存报名状态成功!");
                } else {
                    studentDao.updateStep(student);
                    return Result.success("更新报名状态成功!");
                }
            default:
                log.error("报名信息更新类型错误!");
        }
        return Result.fail("报名信息更新失败!");
    }


    /**
     * 根据学员无纸化报名ID获取学员信息
     * 如果处于退费的状态，进行判断处理是否重新推送无纸化
     * @return
     */
    public boolean upStudentForStatus(String studentId){
        Student entity = studentDao.getByStudentId(studentId);
        //更新报名学员和无纸化之间的学员ID的关系
        Stu stuEntity = stuDao.queryStuPayOkNoTf(entity.getCardNo(), entity.getTrainType());
        if(stuEntity == null){
            return true;
        }
        if(stuEntity != null){
            if(StringUtils.isEmpty(stuEntity.getStudentId())){
                stuDao.updateStudentIdById(studentId,stuEntity.getId()+"");
            }

            //如果是退费的学员，检索报名状态，处理计时的推送
            String status = entity.getStatus();
            if(status.trim().equals("2")){
                String cardNo = entity.getCardNo();
                String trainType = entity.getTrainType();

                List<Stu> list = stuDao.queryPayOkNoTf(cardNo, trainType);
                if(list.size() > 0){//存在又缴费的情况
                    studentDao.updateStatusByStudentId(studentId,0);
                }
            }
        }





        //更新学员信息(当学员信息没有录入或者录入错误的时候，进行学员信息的订正)
        Stu stu = stuDao.getByCardNo(entity.getCardNo(), entity.getCardType());
        if(entity != null){
            if(stu != null){
                boolean flag = false;
                if(StringUtils.isEmpty(stu.getName())){
                    flag = true;
                }else{
                    if(!stu.getName().equals(entity.getName())){
                        flag = true;
                    }
                }

                if(StringUtils.isEmpty(stu.getGender())){
                    flag = true;
                }else{
                    if(!stu.getGender().equals(entity.getGender()+"")){
                        flag = true;
                    }
                }

                if(StringUtils.isEmpty(stu.getAddress())){
                    flag = true;
                }else{
                    if(!stu.getAddress().equals(entity.getAddress())){
                        flag = true;
                    }
                }

                if(StringUtils.isEmpty(stu.getMobile())){
                    flag = true;
                }else{
                    if(!stu.getMobile().equals(entity.getMobile())){
                        flag = true;
                    }
                }


                if(flag){
                    stu.setName(entity.getName());
                    stu.setGender(entity.getGender()+"");
                    stu.setAddress(entity.getAddress());
                    stu.setNationality(entity.getNationality());
                    stu.setMobile(entity.getMobile());
                    stu.setNation(entity.getNation());
                    stu.setLearningCategories(entity.getLearningCategories());
                    stuDao.updateStu(stu);
                    stuDao.updatePayInfoName(entity.getCardNo(),entity.getName());
                }
            }
        }

        return true;
    }


    @Override
    public Result listLatest10() {
        final int COUNT = 10;
        List<Student> studentList = studentDao.list(new HashMap<>(), 0, COUNT);
        return Result.success("success", studentList);
    }
}
